/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.magri.mvc.persistence;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Magri
 */
public class DBConnection {
    
    private static final String driver = "org.postgresql.Driver";
    private static final String url = "jdbc:postgresql://127.0.0.1:5432/pos2012";
    private static final String usuario = "postgres";
    private static final String senha = "postgres123";
    
    private java.sql.Connection connection;

    private static DBConnection instance;
    
    static {
        
        instance = new DBConnection();
        //org.apache.derby.jdbc.ClientDriver.class;
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public static DBConnection getInstance() {
        return instance;
    }
    
    public java.sql.Connection getConnection() throws SQLException {
        if (connection == null) {
            connection = DriverManager.getConnection(url, usuario, senha);
        }
        return connection;
    }
    
    public void fecharConexao() throws SQLException {
        if (connection != null) {
            connection.close();
            connection = null;
        }
    }
    
    
    public static void main(String[] args) {
        try {
            java.sql.ResultSet rs = DBConnection.getInstance().getConnection().prepareStatement("SELECT * FROM CIDADE").executeQuery();
            
            while (rs.next()) {                
                System.out.println("" + rs.getString("NOME") + " - " + rs.getString("UF"));
            }
            
            
            
            System.out.println("conectado");
            DBConnection.getInstance().fecharConexao();
            System.out.println("Conexao fechada com sucesso");
        } catch (SQLException ex) {
            Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
                
    }
}
